<?php

namespace app\admin\utils\controller;

use app\common\controller\BaseController;
use support\Db;
use support\Request;

/**
 * 日志视图报表查看
 */
class LogsViewController extends BaseController
{
    function index(Request $request){

        $date = $request->input('t',date('Y-m-d'));
        $tableName = 'global_log_'.str_replace('-','',$date);


        // ip 汇总
        $projectIpStatisticList = Db::table($tableName)
            ->select('ip',Db::raw('count(1) AS total'))
            ->groupBy('ip')
            ->orderBy('total', 'desc')
            ->take(10)
            ->get()
            ->each(function($item){
                $item->ip_text = ipFind($item->ip);
            })
            ->toArray();

        // 请求数汇总
        $projectUriStatisticList = Db::table($tableName)
            ->select('uri',Db::raw('count(1) AS total'))
            ->groupBy('uri')
            ->orderBy('total', 'desc')
            ->take(10)
            ->get()
            ->toArray();

        // 响应排序
        $projectExecTimeStatisticList = Db::table($tableName)
            ->select('uri','exec_time')
            ->orderBy('exec_time', 'desc')
            ->take(10)
//            ->get()
            ->toSql();
//            ->toArray();
dump($projectExecTimeStatisticList);

        $reData = [
            // 汇总请求数
            'gather'=>[
                'count'=>Db::table($tableName)->count(),
                '500'=>Db::table($tableName)->where(['errcode'=>500])->count(),
                'exec_time'=>Db::table($tableName)->avg('exec_time'),
                'post'=>Db::table($tableName)->where(['method'=>'post'])->count(),
            ],

            // 分时段，请求数
            'errLogList'=>[],
//            'statistic'=>$this->statistic($tableName,$date),

            // ip 汇总
            'projectIpStatisticList'=>$projectIpStatisticList,
            // uri 汇总
            'projectUriStatisticList'=>$projectUriStatisticList,
            // 响应排序
            'projectExecTimeStatisticList'=>$projectExecTimeStatisticList,

            // 请求日志列表
        ];

//        dump($reData);

        return view('/utils/logs_view/index',$reData);

    }


    /**
     * 获取统计图表数据
     * @param $tableName 查询的表名
     * @param $date 查询的时间
     * @return void
     */
    function statistic(Request $request){
        // 统计图表数据
        $date = $request->input('t',date('Y-m-d'));
        $tableName = 'global_log_'.str_replace('-','',$date);

        $intervalData = Db::table($tableName)
            ->select(
                DB::raw('DATE_FORMAT(created_at, "%Y%m%d%H%i") as minute_group'),
                DB::raw('COUNT(*) as count'),
                DB::raw('AVG(exec_time) as avg_exec_time')
            )
            ->groupBy('minute_group')
            ->orderBy('minute_group')
            ->get()
            ->each(function($item){
                $item->avg_exec_time = number_format($item->avg_exec_time,2).'ms';
//                return $item;
            })

            ->toArray();

        $intervalData = array_column($intervalData,null,'minute_group');

        $chartList     = [];
        $time          = strtotime($date);
        $intervalCount = (int)(ceil(time() / 60) * 60 - $time) / 60;
        $intervalCount = $intervalCount > 1440 ? 1440 : $intervalCount;
        for ($i = 0; $i < $intervalCount; $i++) {
            $interval = date('YmdHi', $time + $i * 60);// 按分钟 进行数据统计
            if (empty($intervalData[$interval])) {
                $chartList['time'][$interval]          = date('Y-m-d H:i', $time + $i * 60);
                $chartList['count'][$interval]         = 0;
                $chartList['avg_exec_time'][$interval]         = 0;

            } else {
                $chartList['time'][$interval]          = date('Y-m-d H:i', $time + $i * 60);
                $chartList['count'][$interval]         = $intervalData[$interval]->count;
                $chartList['avg_exec_time'][$interval]         = $intervalData[$interval]->avg_exec_time;
//                $chartList['success_count'][$interval] = $intervalData[$interval]['success_count'];
//                $chartList['error_count'][$interval]   = $intervalData[$interval]['error_count'];
//                $chartList['average_cost'][$interval]  = $intervalData[$interval]['average_cost'];
            }
        }
        $chartList['time']          = array_values($chartList['time'] ?? []);
        $chartList['count']         = array_values($chartList['count'] ?? []);
        $chartList['avg_exec_time'] = array_values($chartList['avg_exec_time'] ?? []);

        return $this->json(0,'ok',$chartList);
    }

}